package com.panda.autotest.core.engine;

import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

import com.panda.autotest.core.datasource.DynamicDataSource;
import com.panda.autotest.core.parse.Step;

public class JdbcHandler extends JdbcDaoSupport {
	private Logger logger = LoggerFactory.getLogger(JdbcHandler.class);

	public Map<String, Object> query(Step step) {
		try {
			DynamicDataSource.setDataSource(step.getSchema());
			String sql = step.getSql();
			Map<String, String> paramMap = step.getParamMap();
			Set<Entry<String, String>> set = paramMap.entrySet();
			for (Entry<String, String> entry : set) {
				sql = sql.replaceAll("\\$\\{" + entry.getKey() + "\\}", entry.getValue());
			}
			logger.info("执行sql:" + sql);
			Map<String, Object> dataMap = this.getJdbcTemplate().queryForMap(sql);
			logger.info("JdbcHandler query " + sql + "dataMap=" + dataMap);
			return dataMap;
		} finally {
			DynamicDataSource.clearDataSource();
		}
	}

	public void update(Step step) {
		try {
			DynamicDataSource.setDataSource(step.getSchema());
			String sql = step.getSql();
			Map<String, String> paramMap = step.getParamMap();
			Set<Entry<String, String>> set = paramMap.entrySet();
			for (Entry<String, String> entry : set) {
				sql = sql.replaceAll("\\$\\{" + entry.getKey() + "\\}", entry.getValue());
			}
			logger.info("执行sql:" + sql);
			this.getJdbcTemplate().update(sql);
		} finally {
			DynamicDataSource.clearDataSource();
		}
	}
}
